package com.tanxi521.com.thenorthtitle.event;

import com.tanxi521.com.thenorthtitle.command.TheNorthTitleCmd;
import com.tanxi521.com.thenorthtitle.entity.TheNorthTitleData;
import com.tanxi521.com.thenorthtitle.entity.TheNorthTitlePlayer;
import com.tanxi521.com.thenorthtitle.sql.dao.TnTitleBaseInfoMapper;
import com.tanxi521.com.thenorthtitle.util.GuiUtil;
import com.tanxi521.com.thenorthtitle.util.VaultApi;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TnTitleListener implements Listener {

    public static final List<Integer> mainSlot = Arrays.asList(1, 4, 7);
    public static final List<String> customizingPlayer = new ArrayList<>();
    public static final List<String> confirmingPlayer = new ArrayList<>();

    @EventHandler
    public void playerJoinEvent(PlayerLoginEvent e) {
        Player player = e.getPlayer();
        TnTitleBaseInfoMapper.initUserTitle(player);
    }

    // 首页
    @EventHandler
    public void mainClickEvent(InventoryClickEvent e) {
        Inventory clickedInventory = e.getClickedInventory();
        if (null == clickedInventory) return;
        String title = clickedInventory.getTitle();
        if (null == title) return;
        if (!"§e§l北境称号".equals(title)) return;

        e.setCancelled(true);
        HumanEntity whoClicked = e.getWhoClicked();
        Player player = (Player) whoClicked;
        int slot = e.getSlot();

        if (1 == slot) GuiUtil.openTitleGui(player, 1, 1);
        if (4 == slot) GuiUtil.openTitleGui(player, 1, 2);
        if (7 == slot) this.customTitle(player);
    }

    private void customTitle(Player player) {

        player.sendMessage("§e【定制称号】请在聊天栏输入你想要的定制称号,可以使用颜色代码(如 &5&l你是gay 的效果是 §5§l你是gay§e )");
        player.sendMessage("§e【定制称号】输入 取消 可退出定制称号");
        String playerName = player.getName();
        customizingPlayer.add(playerName);
    }

    @EventHandler
    public void inputtingTitle(AsyncPlayerChatEvent e) {
        Player player = e.getPlayer();
        String playerName = player.getName();

        if (!customizingPlayer.contains(playerName)) return;
        e.setCancelled(true);

        String message = e.getMessage();
        if ("取消".equals(message)) {
            customizingPlayer.remove(playerName);
            player.sendMessage("§e【定制称号】已取消");
            return;
        }

        String title = removeAmpersandPatterns(message);

        if (title.length() > 8) {
            player.sendMessage("§c称号最大长度不能超过8个字");
            return;
        }
        BaseComponent baseComponent = new TextComponent("§e【定制称号】您当前输入的称号是: " + message + " 点击该条信息确认称号或者重新输入");
        baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{new TextComponent("§e确认创建")}));
        baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tntitle add " + message.replace("§", "&") + " 99999999 70 北境公民 " + playerName + " " + TheNorthTitleCmd.PASSWORD));

        player.spigot().sendMessage(baseComponent);

    }

    public static String removeAmpersandPatterns(String input) {
        return input.replaceAll("&.+?", "");
    }

    private boolean isChineseString(String input) {
        for (char c : input.toCharArray()) if (!isChineseCharacter(c)) return true;
        return false;
    }

    // 检查字符是否是中文字符
    private static boolean isChineseCharacter(char c) {
        return c >= 0x4e00 && c <= 0x9fff;
    }

    // 我的称号
    @EventHandler
    public void selectTitle(InventoryClickEvent e) {
        Inventory clickedInventory = e.getClickedInventory();
        if (null == clickedInventory) return;
        String title = clickedInventory.getTitle();
        if (null == title) return;
        if (!title.startsWith("§2§l我的称号 第")) return;
        int type = 1;
        e.setCancelled(true);
        HumanEntity whoClicked = e.getWhoClicked();
        Player player = (Player) whoClicked;
        int slot = e.getSlot();

        if (slot == 0) {
            GuiUtil.openSelectGui(player);
            return;
        }

        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(title);
        int page = 1;
        if (matcher.find()) page = Integer.parseInt(matcher.group());

        if (slot == 45) {
            GuiUtil.openTitleGui(player, page <= 1 ? 1 : page - 1, type);
            return;
        }
        if (slot == 53) {
            String playerName = player.getName();
            int count = TnTitleBaseInfoMapper.getUserTitlesCount(playerName);
            int pageSize = 28;
            int totalPage = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            GuiUtil.openTitleGui(player, page >= totalPage ? totalPage : page + 1, type);
            return;
        }

        ItemStack item = clickedInventory.getItem(slot);
        ItemMeta itemMeta = item.getItemMeta();
        List<String> lore = itemMeta.getLore();
        if (null == lore || lore.size() == 0) return;
        String idString = lore.get(0);
        Matcher idMatcher = pattern.matcher(idString);
        int titleId = 2;
        if (idMatcher.find()) titleId = Integer.parseInt(idMatcher.group());
        TnTitleBaseInfoMapper.setTitle(player, titleId);
        player.sendMessage("§a你佩戴了称号: " + itemMeta.getDisplayName());
    }

    // 我的称号
    @EventHandler
    public void buyTitle(InventoryClickEvent e) {
        Inventory clickedInventory = e.getClickedInventory();
        if (null == clickedInventory) return;
        String title = clickedInventory.getTitle();
        if (null == title) return;
        if (!title.startsWith("§a§l称号商店 第")) return;
        int type = 2;
        e.setCancelled(true);
        HumanEntity whoClicked = e.getWhoClicked();
        Player player = (Player) whoClicked;
        int slot = e.getSlot();

        if (slot == 0) {
            GuiUtil.openSelectGui(player);
            return;
        }

        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(title);
        int page = 1;
        if (matcher.find()) page = Integer.parseInt(matcher.group());

        if (slot == 45) {
            GuiUtil.openTitleGui(player, page <= 1 ? 1 : page - 1, type);
            return;
        }
        if (slot == 53) {
            String playerName = player.getName();
            int count = TnTitleBaseInfoMapper.getUserTitlesCount(playerName);
            int pageSize = 28;
            int totalPage = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            GuiUtil.openTitleGui(player, page >= totalPage ? totalPage : page + 1, type);
            return;
        }

        ItemStack item = clickedInventory.getItem(slot);
        ItemMeta itemMeta = item.getItemMeta();
        List<String> lore = itemMeta.getLore();
        if (null == lore || lore.size() == 0) return;
        String idString = lore.get(0);
        Matcher idMatcher = pattern.matcher(idString);
        int titleId = 2;
        if (idMatcher.find()) titleId = Integer.parseInt(idMatcher.group());

        if (TnTitleBaseInfoMapper.selectHas(player.getName(), titleId) > 0) {
            player.sendMessage("§c你已经拥有这个称号了");
            return;
        }
        TheNorthTitleData titleData = TnTitleBaseInfoMapper.selectTitleInfo(titleId);
        if (TnTitleBaseInfoMapper.selectHas(player.getName(), Integer.parseInt(titleData.getTitleRelyOn())) <= 0) {
            player.sendMessage("§c你还没有获得该称号的前置称号");
            return;
        }
        if (titleData.getTitlePrice() > VaultApi.getMoney(player)) {
            player.sendMessage("§c你没有足够的金币购买这个称号");
            return;
        }
        TheNorthTitlePlayer theNorthTitlePlayer = new TheNorthTitlePlayer();
        theNorthTitlePlayer.setTitleId(titleId).setPlayerName(player.getName())
                .setAchieveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                .setPlayerUuid(player.getUniqueId().toString());
        if (TnTitleBaseInfoMapper.giveTitle(theNorthTitlePlayer) <= 0) {
            player.sendMessage("§c购买失败，请重试");
        } else {
            VaultApi.takeMoney(player, titleData.getTitlePrice());
            player.sendMessage("§a你购买了称号: " + itemMeta.getDisplayName());
            GuiUtil.openTitleGui(player, page, type);
        }
    }


}
